<template>
  <div class="upload_template">
    <ImgCutter ref="imgCutterModal" @cutDown="cutDown" :crossOrigin="true" :showChooseBtn="false">
            <template #open>
              <!--        @click="selectImage"-->
              <span></span>
<!--              <el-button type="primary" icon="el-icon-upload2" size="small">点击上传</el-button>-->
            </template>
    </ImgCutter>
    <div class="upload_image" v-loading="loading"
         element-loading-text="图片上传中"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">
      <el-image fit="cover" class="image" @click="editImage" v-if="value" :src="value"/>
      <span style="color:#808080;" v-else>无图片</span>
    </div>
  </div>
</template>

<script>
/*
* 单张图片上传组件
* 使用v-model即可双向绑定上传的图片地址
* */
import {uploadUrl} from "@/api"
import axios from "axios";
import ImgCutter from 'vue-img-cutter';

export default {
  name: "upload",
  props: ['value'],
  components: {ImgCutter},
  data() {
    return {
      loading: false
    }
  },
  methods: {
    // 编辑图片
    editImage() {
      let src = this.value;
      let name = decodeURIComponent(src.split('=').pop());
      this.$refs.imgCutterModal.handleOpen({
        name: name,
        src: src
      });
    },
    // 图片裁剪完成后触发
    cutDown(e) {
      console.log(e)
      this.selectImage(e.file);
    },
    // 选择图片
    selectImage(file) {
      let _this = this;
      _this.loading = true;
      let filename = file.name;
      // 使用正则表达式匹配文件后缀
      let extension = filename.match(/\.([^.]+)$/);
      // 如果匹配到了后缀，extension[1] 将包含后缀名，否则为 null
      let suffix = "."
      suffix += extension ? extension[1] : "png";
      const formData = new FormData();
      formData.append('total', 1);
      formData.append('index', 1);
      formData.append('mainway', 'pic');
      formData.append('filename', Date.now() + suffix);
      formData.append('data', file);
      // 使用Axios或其他HTTP库发送请求
      axios.post(uploadUrl, formData, {
        headers: {'Content-Type': 'multipart/form-data'}
      }).then(response => {
        console.log(response)
        _this.$emit('input', response.data.path);
        _this.loading = false;
      }).catch(err => {
        _this.loading = false;
      })
    }
    /*
    selectImage() {
      let _this = this;
      let input = document.createElement('input');
      // 设置 input 类型为文件选择
      input.type = 'file';
      // 设置文件类型为图片
      input.accept = 'image/*';

      // 添加 change 事件监听器，当用户选择文件后执行
      input.addEventListener('change', function () {
        // 检查是否选择了文件
        if (this.files && this.files[0]) {
          // 获取第一个文件
          _this.loading = true;
          let file = this.files[0];
          let filename = file.name;
          // 使用正则表达式匹配文件后缀
          let extension = filename.match(/\.([^.]+)$/);
          // 如果匹配到了后缀，extension[1] 将包含后缀名，否则为 null
          let suffix = "."
          suffix += extension ? extension[1] : "png";
          const formData = new FormData();
          formData.append('total', 1);
          formData.append('index', 1);
          formData.append('mainway', 'pic');
          formData.append('filename', Date.now() + suffix);
          formData.append('data', file);
          // 使用Axios或其他HTTP库发送请求
          axios.post(uploadUrl, formData, {
            headers: {'Content-Type': 'multipart/form-data'}
          }).then(response => {
            console.log(response)
            _this.$emit('input', response.data.path);
            _this.loading = false;
          }).catch(err => {
            _this.loading = false;
          })
        }
      });

      // 触发 input 元素的点击事件，打开文件选择对话框
      input.click();
    }
    */
  }
}
</script>

<style scoped lang="scss">
.upload_template {

  .upload_image {
    width: 100%;
    height: 180px;
    display: flex;
    margin-top: 15px;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    box-shadow: 0 0 10px 1px #bdbcbc;
    overflow: hidden;
    cursor: pointer;

    .image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}
</style>
